package com.totcy.atom.view.fragment;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.totcy.atom.CommonValues;
import com.totcy.atom.R;
import com.totcy.atom.adapter.DailyForecastAdapter;
import com.totcy.atom.adapter.LifeIndexAdapter;
import com.totcy.atom.bean.HeWeatherDailyForecast;
import com.totcy.atom.bean.HeWeatherHourly;
import com.totcy.atom.bean.HeWeatherLifeStyle;
import com.totcy.atom.bean.HeWeatherNow;
import com.totcy.atom.presenter.WeatherPresenter;
import com.totcy.atom.presenter.contract.WeatherContract;
import com.totcy.atom.utils.glide.GlideUtil;
import com.totcy.atom.utils.weather.WeatherConvert;
import com.totcy.baselibrary.adapter.divider.RecycleViewDivider;
import com.totcy.baselibrary.utils.KeyBordUtil;
import com.totcy.baselibrary.utils.SPUtil;
import com.totcy.baselibrary.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.totcy.atom.R.id.refresh;
import static com.totcy.atom.R.id.tv_windType;

/**
 * description : 天气
 *
 * @author : Totcy
 * @date : 2018/1/18 14:50
 * @update : 2018/1/18
 */

public class WeatherFragment extends BaseFragment<WeatherContract.View, WeatherPresenter> implements WeatherContract.View, OnRefreshListener {

    @BindView(R.id.iv_weatherScene)
    ImageView ivWeatherScene;
    @BindView(refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_Temperature)
    TextView tvTemperature;
    @BindView(R.id.tv_weatherNow)
    TextView tvWeatherNow;
    @BindView(R.id.iv_weatherNow)
    ImageView ivWeatherNow;
    @BindView(tv_windType)
    TextView tvWindType;
    @BindView(R.id.tv_windLevel)
    TextView tvWindLevel;
    @BindView(R.id.tv_humidity)
    TextView tvHumidity;
    @BindView(R.id.tv_somatosensoryTemperature)
    TextView tvSomatosensoryTemperature;
    @BindView(R.id.rv_weatherDay)
    RecyclerView rvWeatherDay;
    @BindView(R.id.rv_weatherIndex)
    RecyclerView rvWeatherIndex;

    private DailyForecastAdapter dailyForecastAdapter;
    private List<HeWeatherDailyForecast> dailyForecasts = new ArrayList<>();

    private LifeIndexAdapter lifeIindexAdapter;
    private List<HeWeatherLifeStyle> heWeatherLifeStyles = new ArrayList<>();

    private String currentCondCode = "";//当前天气code
    //是否模糊
    private boolean isBlur = false;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_weather;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvWeatherDay.setLayoutManager(layoutManager);
        //分割线
        rvWeatherDay.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, (int) (getResources().getDisplayMetrics().density * 0.5),
                ContextCompat.getColor(getActivity(), R.color.cut_line_color_transparent_75))
                .setDrawTop(false));
        rvWeatherDay.setAdapter(dailyForecastAdapter = new DailyForecastAdapter(getActivity(), dailyForecasts));

        //生活指数
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvWeatherIndex.setLayoutManager(gridLayoutManager);
        rvWeatherIndex.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, (int) (getResources().getDisplayMetrics().density * 0.5),
                ContextCompat.getColor(getActivity(), R.color.cut_line_color_transparent_75))
                .setDrawTop(false));
        rvWeatherIndex.setAdapter(lifeIindexAdapter = new LifeIndexAdapter(getActivity(), heWeatherLifeStyles));
        refreshLayout.setOnRefreshListener(this);
        //自动刷新
        refreshLayout.autoRefresh(150);
        //显示地址
        tvAddress.setText((String) SPUtil.get(getActivity(), CommonValues.KEY_WEATHER_ADDRESS, ""));
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        getPresenter().getWeatherInfoList((String) SPUtil.get(getActivity(), CommonValues.KEY_WEATHER_ADDRESS, "上海"));
    }

    /**
     * 实时天气
     *
     * @param weatherNow
     */
    @Override
    public void onNowWeather(HeWeatherNow weatherNow) {
        refreshLayout.finishRefresh();

        //地区显示
        tvAddress.setText(weatherNow.getAddress());
        tvTemperature.setText(weatherNow.getTmp());
        tvWeatherNow.setText(weatherNow.getCond_txt());
        tvWindType.setText(weatherNow.getWind_dir());
        tvWindLevel.setText(weatherNow.getWind_sc());
        tvHumidity.setText(weatherNow.getHum() + "%");
        tvSomatosensoryTemperature.setText(String.format("%s℃", weatherNow.getFl()));

        currentCondCode = weatherNow.getCond_code();
        GlideUtil.loadImageNoPlaceholder(getActivity(), WeatherConvert.weatherCode2Local(currentCondCode).getIconRes(), ivWeatherNow, true, R.drawable.weizhi);

        refreshScene();
    }

    /**
     * 现场图，背景图，根据天气状态切换显示
     */
    private void refreshScene() {
        GlideUtil.loadImage(getActivity(),
                WeatherConvert.getWeatherBackground(currentCondCode, isBlur),
                ivWeatherScene, R.drawable.default_weather_scene_preview);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshScene();
        }
    }

    /**
     * 3-7天天气预报
     *
     * @param dailyForecasts
     */
    @Override
    public void on3To7Weather(List<HeWeatherDailyForecast> dailyForecasts) {
        this.dailyForecasts.clear();
        this.dailyForecasts.addAll(dailyForecasts);
        dailyForecastAdapter.notifyDataSetChanged();
    }

    /**
     * 逐小时预报
     *
     * @param weatherHourlies
     */
    @Override
    public void onHourlyWeather(List<HeWeatherHourly> weatherHourlies) {

    }

    /**
     * 生活指数
     *
     * @param lifeStyles
     */
    @Override
    public void onLifeIndex(List<HeWeatherLifeStyle> lifeStyles) {
        heWeatherLifeStyles.clear();
        heWeatherLifeStyles.addAll(lifeStyles);
        lifeIindexAdapter.notifyDataSetChanged();
    }

    /**
     * 这里获取数据失败
     *
     * @param code
     * @param message
     */
    @Override
    public void onDataFail(int code, String message) {
        refreshLayout.finishRefresh(false);
        ToastUtil.showToast(getActivity(), message);
    }

    public void onSearch(String query) {

        if (TextUtils.isEmpty(query)) {
            ToastUtil.showToast(getActivity(), "请输入搜索关键字");
            return;
        }
        showProgress("加载中");
        // 搜索功能主体
        getPresenter().getWeatherInfoList(query);

    }

    @Override
    public void showProgress(String message) {
        super.showProgress(message);

    }

    @Override
    public void dismissProgress() {
        super.dismissProgress();
    }
}
